import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  ScopeContext,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { ExtendedModalApi } from '@vben/common-ui';
import type { Undefinedable } from '@vben/types';

import type { DefTenantModel } from '#/api';

import { ref } from 'vue';

import { compute } from '@fast-crud/fast-crud';
import { Tag } from 'ant-design-vue';

import { asyncFindUrlById, MyTenantApi } from '#/api';
import cities from '#/api/common/cities.json';
import { DictEnum, FileBizTypeEnum } from '#/enums/commonEnum';
import { TenantStatusEnum } from '#/enums/system';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
  STATE_CONSTANT_DICT,
} from '#/plugins/fast-crud/common';
import { dateUtil } from '#/utils/dateUtil';

interface ContextRef {
  bindUserRef: Ref<Undefinedable<ExtendedModalApi>>;
  toExamineRef: Ref<Undefinedable<ExtendedModalApi>>;
  initDataRef: Ref<Undefinedable<ExtendedModalApi>>;
  linkDataSourceRef: Ref<Undefinedable<ExtendedModalApi>>;
}

export function createCrudOptions(
  props: CreateCrudOptionsProps<DefTenantModel.DefTenantResultVO, ContextRef>,
): CreateCrudOptionsRet<DefTenantModel.DefTenantResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  const { createConfirm, createMessage } = useMessage();

  return {
    crudOptions: {
      form: {
        labelCol: { span: null, style: { minWidth: '130px' } },
        wrapper: {
          is: 'a-drawer',
          width: '70%',
          draggable: false,
        },
      },
      request: {
        pageRequest: MyTenantApi.pageRequest,
        addRequest: MyTenantApi.addRequest,
        editRequest: MyTenantApi.editRequest,
        delRequest: MyTenantApi.delRequest,
        infoRequest: MyTenantApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: { text: '注册企业' },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: MyTenantApi.removeFn,
          }),
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: 140,
        buttons: {
          view: {
            dropdown: true,
            show: true,
          },
          copy: { show: false },
          withdraw: {
            show: compute((context: ComputeContext) => {
              return [TenantStatusEnum.WAITING].includes(context.row?.status);
            }),
            text: '撤回',
            size: 'small',
            type: 'link',
            dropdown: true,
            async click(context) {
              createConfirm({
                iconType: 'warning',
                content: '是否确认要撤回审批',
                onOk: async () => {
                  await MyTenantApi.updateStatus({
                    id: context.row.id,
                    status: TenantStatusEnum.WITHDRAW,
                  });
                  createMessage.success('撤回成功');
                  props.crudExpose.doRefresh();
                },
              });
            },
          },

          relaunch: {
            show: compute((context: ComputeContext) => {
              return [
                TenantStatusEnum.REFUSE,
                TenantStatusEnum.WITHDRAW,
              ].includes(context.row?.status);
            }),
            text: '发起审批',
            size: 'small',
            type: 'link',
            dropdown: true,
            async click(context) {
              createConfirm({
                iconType: 'warning',
                content: '是否确认要重新发起审批',
                onOk: async () => {
                  await MyTenantApi.updateStatus({
                    id: context.row.id,
                    status: TenantStatusEnum.WAITING,
                  });
                  createMessage.success('发起审批成功');
                  props.crudExpose.doRefresh();
                },
              });
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        logo: {
          title: 'logo',
          type: 'cropper-uploader',
          form: {
            component: {
              valueType: 'key',
              buildUrl: async (res: any) => {
                const file = await asyncFindUrlById(res);
                return file.data;
              },
              uploader: {
                param: {
                  bizType: FileBizTypeEnum.DEF_TENANT_LOGO,
                },
              },
            },
            col: { span: 24 },
          },
          column: { show: false, columnSetDisabled: true },
        },
        creditCode: {
          title: $t('devOperation.tenant.defTenant.creditCode'),
          type: 'text',
          column: { show: false },
        },
        name: {
          title: $t('devOperation.tenant.defTenant.name'),
          type: 'text',
          search: { show: true },
        },
        registerType: {
          title: $t('devOperation.tenant.defTenant.registerType'),
          type: 'dict-radio',
          dict: backendDict({
            type: 'DefTenantRegisterTypeEnum',
            isEnum: true,
          }),
          form: { show: false },
          viewForm: { show: true },
          column: { width: 80 },
        },
        abbreviation: {
          title: $t('devOperation.tenant.defTenant.abbreviation'),
          type: 'text',
          column: { show: false },
        },

        expirationTime: {
          title: $t('devOperation.tenant.defTenant.expirationTime'),
          type: 'datetime',
          form: {
            show: false,
            helper: {
              text: '有效期为空表示永久有效',
            },
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = value;
            }
          },
          column: {
            width: 180,
            show: true,
            formatter: (context: ScopeContext) => {
              const record = context.row;
              if (record.expirationTime) {
                if (dateUtil(record.expirationTime).isBefore(Date.now())) {
                  return <Tag color="error">已过期</Tag>;
                } else if (
                  dateUtil(record.expirationTime).isBefore(
                    dateUtil().add(30, 'days'),
                  )
                ) {
                  const duration = dateUtil.duration(
                    dateUtil(record.expirationTime).diff(Date.now()),
                  );
                  if (duration.days() > 0) {
                    return (
                      <Tag color="warning">{duration.days() + 1}天后到期</Tag>
                    );
                  }
                  return (
                    <Tag color="warning">{duration.hours()}小时后到期</Tag>
                  );
                }
                return <Tag color="processing">{record.expirationTime}</Tag>;
              }

              return <Tag color="success">永久有效</Tag>;
            },
          },
        },
        state: {
          title: $t('devOperation.tenant.defTenant.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          search: { show: true },
          addForm: { value: true },
          form: { show: false, component: { optionName: 'a-radio-button' } },
          column: { width: 80 },
        },

        contactPerson: {
          title: $t('devOperation.tenant.defTenant.contactPerson'),
          type: 'text',
          column: { show: false },
        },
        contactPhone: {
          title: $t('devOperation.tenant.defTenant.contactPhone'),
          type: 'text',
          column: { show: false },
        },
        contactEmail: {
          title: $t('devOperation.tenant.defTenant.contactEmail'),
          type: 'text',
          column: { show: false },
        },
        area: {
          title: '地区',
          type: 'text',
          column: { show: false },
          form: {
            component: {
              name: 'a-cascader',
              options: cities,
              checkStrategy: 'child',
            },
          },
        },
        address: {
          title: $t('devOperation.tenant.defTenant.address'),
          type: 'text',
          column: { show: false },
        },
        status: {
          title: $t('devOperation.tenant.defTenant.status'),
          type: 'dict-select',
          dict: backendDict({
            type: DictEnum.DefTenantStatusEnum,
            isEnum: true,
          }),
          search: { show: true },
          form: { show: false },
          column: { show: true, width: 120 },
        },

        describe: {
          title: $t('devOperation.tenant.defTenant.describe'),
          type: 'textarea',
          column: { show: false },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}
